<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Filters\UserFilter;
use App\Filters\UserRoleFilter;
use App\Http\Requests\UserRequest;
use App\Http\Resources\UserCollection;
use App\Http\Resources\UserResource;
use App\Http\Resources\UserRoleCollection;
use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * 管理员模块
 * Class UserController
 * @package App\Http\Controllers
 */
class UserController extends Controller
{

    /**
     * 列表
     * @param UserFilter $filter
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(UserFilter $filter)
    {
        $paginate = User::filter($filter)->whereNotIn('id', UserService::systemAdminIdList())->paginate($this->pageSize());
        $result = UserCollection::make($paginate)->only(['id', 'username', 'name', 'role_ids','phone_number','email', 'role_name_list', 'last_login_time', 'login_fail_times', 'status', 'created_at', 'updated_at'])->toArray(null);
        return $this->success('', $result);
    }

    /**
     * 添加
     * @param UserRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(UserRequest $request)
    {
        $data = $request->validate('store');
        DB::beginTransaction();
        try {
            UserService::updateOrCreate(null, $data);
            DB::commit();
            return $this->successStored();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorStored();
        }
    }

    /**
     * 查看
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(User $user)
    {
        if ($user->sys) return $this->errorHttpNotFound();
        $userResource = UserResource::make($user)->only(['id', 'name', 'username', 'role_ids', 'avatar_image', 'description', 'phone_number', 'email', 'status'])->toArray(null);
        return $this->success('', $userResource);
    }

    /**
     * 更新
     * @param UserRequest $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(UserRequest $request, User $user)
    {
        if ($user->sys) return $this->errorHttpNotFound();
        $data = $request->validate('update');
        DB::beginTransaction();
        try {
            UserService::updateOrCreate($user, $data);
            DB::commit();
            return $this->successUpdated();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorUpdated();
        }
    }

    /**
     * @param $id // 1或'1,2'
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $between = explode(',', $id);
            $systemAdminIdList = UserService::systemAdminIdList();
            $filtered = collect($between)->filter(function ($value, $key) use ($systemAdminIdList) {
                return !in_array($value, $systemAdminIdList);
            })->all();
            User::destroy($filtered);
            DB::commit();
            return $this->successDestoryed();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorDestoryed();
        }
    }

    /**
     * 更新状态
     * @param UserRequest $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateStatus(UserRequest $request, User $user)
    {
        if ($user->sys) return $this->errorHttpNotFound();
        $data = $request->validate('updateStatus');
        if (!$user->update($data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 个人资料
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function profile(Request $request)
    {
        $user = Auth::user();
        $userResource = UserResource::make($user)->only(['id', 'name', 'username', 'avatar_image', 'description', 'phone_number', 'email', 'roles', 'created_at', 'sys', 'last_login_time', 'permissions'])->toArray($request);
        return $this->success('', $userResource);
    }

    /**
     * 清空登录错误次数
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearLoginFailTimes(User $user)
    {
        if ($user->sys) return $this->errorHttpNotFound();
        if (!UserService::clearLoginFailTimes($user)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 更新个人资料
     * @param UserRequest $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateProfile(UserRequest $request, User $user)
    {
        $data = $request->validate('updateProfile');
        if (!UserService::updateProfile($user, $data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 角色模块-管理员列表
     * @param Role $role
     * @param UserRoleFilter $filter
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleUserList(Role $role, UserRoleFilter $filter, Request $request)
    {
        $paginate = UserRole::join('user', 'user_role.user_id', '=', 'user.id')->select(['user.*'])->where('user_role.role_id', $role->id)->filter($filter)->paginate($this->pageSize());
        $result = UserRoleCollection::make($paginate)->toArray($request);
        return $this->success('', $result);
    }

}
